package com.gaoyi.crm.vm;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.gaoyi.crm.R;
import com.gaoyi.crm.apiresult.ApiResultData;
import com.gaoyi.crm.callback.OnResultListener;
import com.gaoyi.crm.constant.ApiStatus;
import com.gaoyi.crm.db.entity.ItemNoStore;
import com.gaoyi.crm.repository.ItemNoStoreRepository;
import com.gaoyi.crm.util.StringUtil;
import com.gaoyi.crm.util.ToastUtil;
import com.gaoyi.crm.vm.base.BaseViewModel;
import com.google.gson.reflect.TypeToken;

public class ScanDoneViewModel extends BaseViewModel {

    MutableLiveData<ItemNoStore> mItemNoStore;
    MutableLiveData<Integer> mResultCode;
    ItemNoStoreRepository mRepository;

    public MutableLiveData<ItemNoStore> getItemNoStore() {
        if (mItemNoStore == null) {
            mItemNoStore = new MutableLiveData<>();
        }
        return mItemNoStore;
    }

    public MutableLiveData<Integer> getResultCode() {
        if (mResultCode == null) {
            mResultCode = new MutableLiveData<>();
        }
        return mResultCode;
    }

    public ScanDoneViewModel(@NonNull Application application) {
        super(application);
        mRepository = new ItemNoStoreRepository();
    }

    public void getItemNoStore(String itemNo){
        if (getView() != null) {
            getView().showLoading();
        }
        mRepository.getItemNo(itemNo, new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                ApiResultData<ItemNoStore> apiResultData = (ApiResultData<ItemNoStore>) apiResult;
                if (apiResultData.getStatus() != ApiStatus.SUCCESS) {
                    ToastUtil.showToast(StringUtil.getString(R.string.item_no_no_record,itemNo));
                    mResultCode.setValue(ApiStatus.FAIL);
                    return;
                }
                ItemNoStore data = apiResultData.getData();
                if (data == null) {
                    mResultCode.setValue(ApiStatus.FAIL);
                    ToastUtil.showToast(StringUtil.getString(R.string.item_no_no_record,itemNo));
                    return;
                }
                mItemNoStore.setValue(data);
            }

            @Override
            public void onFails(Exception e) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                ToastUtil.showToast(R.string.network_error);
                mResultCode.setValue(ApiStatus.FAIL);
            }
        },new TypeToken<ApiResultData<ItemNoStore>>(){}.getType());
    }
}
